package com.yyp.car.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.yyp.car.Idao.ICarTypeDao;
import com.yyp.car.Iservice.ICarTypeService;
import com.yyp.car.dao.SchoolDao;
import com.yyp.car.model.CarType;
import com.yyp.car.model.School;

@Service("carTypeService")
public class CarTypeService implements ICarTypeService {
	@Resource(name = "carTypeDao")
	private ICarTypeDao carTypeDao;
	@Resource(name = "schoolDao")
	private SchoolDao schoolDao;

	@Override
	public List<CarType> listCarType() {
		return carTypeDao.listCarType();
	}

	@Override
	public CarType addCarType(CarType carType) {
		return carTypeDao.add(carType);
	}

	@Override
	public void updateCarType(CarType carType,String oldName) {
		System.out.println(carType.getName());
		List<School> schools = schoolDao.listSchool();
		for (School sc : schools) {
			if (sc.getCarTypes().contains(" "+oldName)) {
				sc.setCarTypes(sc.getCarTypes().replace(" "+oldName," "+carType.getName()));
				schoolDao.update(sc);
			}
		}
		carTypeDao.update(carType);
	}

	@Override
	public CarType load(int id) {
		return carTypeDao.load(id);
	}

	@Override
	public void delete(int id) {
		CarType ct = carTypeDao.load(id);
		List<School> schools = schoolDao.listSchool();
		for (School sc : schools) {
			if (sc.getCarTypes().contains(" "+ct.getName())) {
				sc.setCarTypes(sc.getCarTypes().replace(" "+ct.getName(), ""));
				schoolDao.update(sc);
			}
		}
		carTypeDao.delete(id);
	}

}
